import { getZkbbLIst, MAGIC_SUCC_CODE, addZkbbList } from "@api"
import { uuid } from "@ui/utils/win"
import { yqList } from "@utils/dic"

export function use() {
  const yqid = ref<string>(''),
    tableData = ref<any[]>([]),
    currentRow = ref<any>(),
    addShow = ref<boolean>(false),
    addFormData = ref({ jsm: '12' }),
    formTable = ref(),
    addModule = ref()
  watch(() => yqid.value, query)
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function sure(data: any[]) {
    setFormData(tableData.value.concat(data || []))
    if (addModule)
      addModule.value.clear()
    addShow.value = false
  }
  function query() {
    const id = yqid.value
    if (id) {
      getZkbbLIst({ yqid: id }).then(({ data: { list } }) => {
        tableData.value = list
      })
    } else {
      tableData.value = []
    }
  }
  function add() {
    const id = yqid.value
    if (id) {
      tableData.value.push({ yqid: id, yqmc: (yqList.value.filter((it: any) => it.id == id)[0] || {}).yqmc || '', id: uuid(), fs: 1 })
    } else {
      ElMessage({ type: 'warning', message: '请先选择要操作的仪器' })
    }
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { id } = obj
      tableData.value = tableData.value.filter(it => it.id != id)
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function save() {
    addZkbbList({ data: tableData.value, yqid: yqid.value }).then(({ code, data, message }) => {
      if (code === MAGIC_SUCC_CODE) {
        ElMessage({ type: 'success', message: '新增成功' })
        query()
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  return { yqid, tableData, del, currentRow, query, save, add, addShow, addFormData, sure, formTable, addModule }
}